package com.springdoor.wx.api.controller;

import com.springdoor.wx.api.entity.WxUser;
import com.springdoor.wx.api.service.WxUserService;
import com.springdoor.wx.config.WxConfig;
import com.springdoor.wx.config.annotation.Log;
import com.springdoor.wx.constant.Constants;
import com.springdoor.wx.constant.enums.BusinessType;
import com.springdoor.wx.core.controller.BaseController;
import com.springdoor.wx.core.domain.AjaxResult;
import com.springdoor.wx.core.domain.entity.LoginUser;
import com.springdoor.wx.utils.string.StringUtils;
import com.springdoor.wx.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("upload")
public class FileUploadController extends BaseController {

    @Autowired
    private WxUserService userService;

    @PostMapping("avatar")
    @Log(title = "小程序用户->头像上传+修改客户信息", businessType = BusinessType.UPDATE)
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file
            , @RequestParam("nickName") String nickName
            , @RequestParam("gender") String gender
            , @RequestParam("phone") String phone
            , @RequestParam("email") String email
    ) {
        if (file.isEmpty()) {
            return AjaxResult.error("上传失败，文件为空");
        }
        try {
            String originalFilename = file.getOriginalFilename();
            String [] fileTypes = { "jpeg", "jpg", "png", "gif" };
            if (!StringUtils.endsWithAny(originalFilename, fileTypes)) {
                return AjaxResult.error("上传失败，图片类型错误！");
            }
            String profile = WxConfig.getProfile();
            Path uploadPath = Paths.get(profile);
            if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
            }
            String[] split = StringUtils.split(originalFilename, ".");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String fileName = sdf.format(new Date()) + "_" + IdUtils.fastSimpleUUID() + "." + split[split.length - 1];
            Path filePath = uploadPath.resolve(fileName);
            file.transferTo(filePath);
            String avatarUrl = Constants.RESOURCE_PREFIX + "/" + fileName;

            LoginUser loginUser = getLoginUser();
            WxUser param = new WxUser();
            param.setUserId(loginUser.getUserId());
            param.setUserName(nickName);
            param.setSex(gender);
            param.setPhone(phone);
            param.setEmail(email);
            param.setAvatar(avatarUrl);
            userService.updateWxUser(loginUser, param);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", avatarUrl);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", fileName);
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("头像上传失败");
        }
    }
}
